package com.toy.core.dao.support;


import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.DbCallback;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.toy.core.ToyConstants;
import com.toy.core.util.SpringContextHolder;

public class MongoSeq {
	
	public static long getSeq(){
		MongoTemplate mongoTemplate = SpringContextHolder.getBean(MongoTemplate.class);
		return mongoTemplate.execute(new DbCallback<Long>(){
			public Long doInDB(DB db) throws MongoException, DataAccessException {
				DBCollection c = db.getCollection( ToyConstants.TABLE_COUNT);
				DBObject query = BasicDBObjectBuilder.start("_id", 1).get();
		        DBObject update = BasicDBObjectBuilder.start().push("$inc").add("seq", 1).get();
		        DBObject count = c.findAndModify(query, null, null, false, update, true, true);
				return Long.valueOf(count.get("seq").toString());
			}});
	}

}
